//说明：主从一对多结构表基本修改页方法

import { EntityMasterCreateDto } from '/@/api/baseMode/EntityMasterCreateDto';
import { isNull, clog, showSuccess } from '/@/utils/index';
import { ElMessageBox } from 'element-plus';
/**
 * 主从一对多结构表基本修改页方法
 * @param entity 主表实体
 * @param detailEntity 子表实体（传入数组）
 * @param GetDateById 获取单据信息的接口
 * @param Save 保存接口
 * @param ValidateFun 校验方法
 * @returns
 */
export default function EditMSControls<T1 extends EntityMasterCreateDto, T2>(entity: T1, detailEntity: T2[], GetDateById: Function, Save: Function, ValidateFun?: Function) {
	let master = reactive<T1>(entity);
	let detailList = reactive<T2[]>(detailEntity);
	let isSave = ref<boolean>(false);
	/**
	 * 新增操作，清空数据
	 */
	let resetData = () => {
		Object.keys(master as any).forEach((key) => {
			(master as any)[key] = undefined;
		});
		detailList.splice(0, detailList.length);
		isSave.value = false;
	};

	/**
	 * 获取单据信息
	 * @param row
	 */
	const itemChange = (row: any) => {
		if (row) {
			GetDateById(row.billNo).then((re: any) => {
				Object.keys(master as any).forEach((key) => {
					(master as any)[key] = (re.masterMessage as any)[key];
				});
				detailList.splice(0, detailList.length);
				detailList.push(...re.detailMessage);
				isSave.value = true;
			});
		}
	};

	const edit = () => {
		if (master.billNo && master.billStatus == 'SaveStatus') {
			isSave.value = false;
		}
	};
	/**
	 * 提交单据
	 * @param billStatus 单据状态
	 * @returns
	 */
	const saveBill = async (billStatus: string = 'SaveStatus') => {
		// 如果有传入校验方法，则先进行校验
		if (ValidateFun) {
			let isValid = await ValidateFun();
			if (!isValid) {
				return;
			}
		}

		let param = {
			masterMessage: {
				...master,
				billStatus: billStatus,
			},
			detailMessage: detailList,
		};
		Save(param).then((re: any) => {
			showSuccess();
			itemChange(re.masterMessage);
		});
	};

	const cancelBill = () => {
		ElMessageBox.confirm('是否确认作废单据?').then(() => {
			let param = {
				masterMessage: {
					...master,
					billStatus: 'VoidStatus',
				},
				detailMessage: detailList,
			};
			Save(param).then((re: any) => {
				showSuccess();
				itemChange(re.masterMessage);
			});
		});
	};

	return {
		master,
		detailList,
		resetData,
		itemChange,
		saveBill,
		edit,
		isSave,
		cancelBill,
	};
}
